package com.derbysoft.dswitch.adapter.ihg.web.action.admin.setting.freemeal;

import com.derbysoft.dswitch.adapter.ihg.common.domain.FreeMealStrategy;
import com.derbysoft.dswitch.adapter.ihg.common.repository.FreeMealStrategyRepository;
import com.derbysoft.dswitch.adapter.ihg.web.action.support.BaseAction;
import com.derbysoft.remote.dswitch.hotel.constants.FreeMealType;
import com.derbysoft.remote.dswitch.hotel.constants.FreeMealUnit;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * User: jason
 * Date: 2013-01-06
 */
public class AddAction extends BaseAction {
    private static final String IMPORT_VIEW = "import";
    private static final int MAX_LINES = 500;
    @Autowired
    private FreeMealStrategyRepository freeMealStrategyRepository;

    private FreeMealStrategy freeMealStrategy;

    private String freeMealStrategies;

    private String message;

    @Action("add")
    public String execute() {
        if (incorrectInput(freeMealStrategy)) {
            message = "inputError !!";
            return ADD;
        }
        FreeMealStrategy existed = freeMealStrategyRepository.load(freeMealStrategy.getChannelPattern(), freeMealStrategy.getHotelPattern(), freeMealStrategy.getRatePlanPattern(), freeMealStrategy.getRoomTypePattern());
        if (existed != null) {
            message = "FreeMealStrategy was Existed !!";
            return ADD;
        }
        freeMealStrategyRepository.save(freeMealStrategy);
        return LIST;
    }

    @Action("importView")
    public String importView() {
        return IMPORT_VIEW;
    }

    @Action("view")
    public String view() {
        return ADD;
    }

    @Action("batchImport")
    public String importAction() {
        if (StringUtils.isBlank(freeMealStrategies)) {
            setMessage("invalid lines");
            return IMPORT_VIEW;
        }
        StringBuilder builder = new StringBuilder();
        Map<String, FreeMealStrategy> freeMealStrategyMap = new HashMap<String, FreeMealStrategy>();
        String[] lines = freeMealStrategies.replace("\r\n", "\n").split("\n");
        for (int lineNumber = 0; lineNumber < lines.length && lineNumber < MAX_LINES; lineNumber++) {
            String[] columns = lines[lineNumber].split("\\|");
            if (columns == null || (columns.length != 8 && columns.length != 7)) {
                builder.append(String.format("<span style=\"color: #ff0000;font-family:Consolas;font-weight: bold;\">[%d]. error line :[ %s ]</span>", lineNumber + 1, lines[lineNumber])).append("<br>");
                continue;
            }
            String[] trimmedColumns = trimAll(columns);
            String channelPattern = trimmedColumns[0];
            String hotelPattern = trimmedColumns[1];
            String ratePlanPattern = trimmedColumns[2];
            String roomTypePattern = trimmedColumns[3];
            FreeMealStrategy existed = freeMealStrategyRepository.load(channelPattern, hotelPattern, ratePlanPattern, roomTypePattern);
            if (existed != null) {
                builder.append(String.format("<span style=\"color: #ff0000;font-family:Consolas;font-weight: bold;\">[ %s-%s-%s-%s ] has been existed !!</span>", channelPattern, hotelPattern, ratePlanPattern, roomTypePattern)).append("<br>");
                continue;
            }
            FreeMealType type = StringUtils.isBlank(trimmedColumns[4]) ? null : FreeMealType.valueOf(trimmedColumns[4].toUpperCase());
            FreeMealUnit freeMealUnit = StringUtils.isBlank(trimmedColumns[5]) ? null : FreeMealUnit.valueOf(trimmedColumns[5].toUpperCase());
            FreeMealStrategy newFreeMealStrategy = new FreeMealStrategy();
            newFreeMealStrategy.setChannelPattern(channelPattern);
            newFreeMealStrategy.setHotelPattern(hotelPattern);
            newFreeMealStrategy.setRatePlanPattern(ratePlanPattern);
            newFreeMealStrategy.setRoomTypePattern(roomTypePattern);
            newFreeMealStrategy.setType(type);
            newFreeMealStrategy.setUnit(freeMealUnit);
            int quantity = StringUtils.isBlank(trimmedColumns[6]) || !NumberUtils.isDigits(trimmedColumns[6]) ? 0 : Integer.parseInt(trimmedColumns[6]);
            newFreeMealStrategy.setQuantity(quantity);
            newFreeMealStrategy.setDescription(trimmedColumns[7]);
            freeMealStrategyMap.put(String.format("%s-%s-%s-%s", channelPattern, hotelPattern, ratePlanPattern, roomTypePattern), newFreeMealStrategy);
            builder.append(String.format("<span style=\"color: #0000ff;font-family:Consolas;font-weight: bold;\">[ %s-%s-%s-%s ] : save done !!</span>", channelPattern, hotelPattern, ratePlanPattern, roomTypePattern)).append("<br>");
        }
        freeMealStrategyRepository.saveAll(new ArrayList<FreeMealStrategy>(freeMealStrategyMap.values()));
        setMessage(builder.toString());
        return IMPORT_VIEW;
    }

    private String[] trimAll(String[] columns) {
        String[] newColumns = new String[columns.length];
        for (int i = 0; i < columns.length; i++) {
            newColumns[i] = StringUtils.trim(columns[i]);
        }
        return newColumns;
    }

    private boolean incorrectInput(FreeMealStrategy freeMealStrategy) {
        return StringUtils.isBlank(StringUtils.trim(freeMealStrategy.getChannelPattern())) ||
                StringUtils.isBlank(StringUtils.trim(freeMealStrategy.getHotelPattern())) ||
                StringUtils.isBlank(StringUtils.trim(freeMealStrategy.getRatePlanPattern())) ||
                StringUtils.isBlank(StringUtils.trim(freeMealStrategy.getRoomTypePattern()));
    }

    public String getFreeMealStrategies() {
        return freeMealStrategies;
    }

    public void setFreeMealStrategies(String freeMealStrategies) {
        this.freeMealStrategies = freeMealStrategies;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public FreeMealStrategy getFreeMealStrategy() {
        return freeMealStrategy;
    }

    public void setFreeMealStrategy(FreeMealStrategy freeMealStrategy) {
        this.freeMealStrategy = freeMealStrategy;
    }
}
